package com.msunsoft.dataset.dictionary.validator;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.ui.core.database.dialog.DatabaseExplorerDialog;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.spoon.job.JobGraph;
import org.pentaho.di.ui.trans.step.BaseStepDialog;

public class ValidatorDialog extends BaseStepDialog implements StepDialogInterface {
  private static Class<?> PKG = ValidatorMeta.class; // for i18n purposes, needed by Translator2!!

	
	private CCombo       wConnection;

	private Label        wlTable,diclTable;
	private Button       wbTable,dicbTable;
	private TextVar      wTable,dicTable;
	private FormData     fdlTable, fdTable;


  private FormData fdbTable;

  private ValidatorMeta validator;
  private boolean changedInDialog;

  private Label wlPosition;
  private FormData fdlPosition;

  public ValidatorDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
    super( parent, (BaseStepMeta) in, transMeta, sname );
    validator = (ValidatorMeta) in;
  }

  public String open() {
    Shell parent = getParent();
    Display display = parent.getDisplay();

    shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
    props.setLook( shell );
    setShellImage( shell, validator );

    ModifyListener lsMod = new ModifyListener() {
      public void modifyText( ModifyEvent e ) {
        changedInDialog = false; // for prompting if dialog is simply closed
        validator.setChanged();
      }
    };
    changed = validator.hasChanged();

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout( formLayout );
    shell.setText( "字典校验" );

    int left = 12;
    int margin = Const.MARGIN;

    // Stepname line
    wlStepname = new Label( shell, SWT.RIGHT );
    wlStepname.setText( "步骤名称" );
    props.setLook( wlStepname );
    fdlStepname = new FormData();
    fdlStepname.left = new FormAttachment( 0, 0 );
    fdlStepname.right = new FormAttachment( left-2, margin );
    fdlStepname.top = new FormAttachment( 0, 2*margin );
    wlStepname.setLayoutData( fdlStepname );
    wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
    wStepname.setText( stepname );
    props.setLook( wStepname );
    wStepname.addModifyListener( lsMod );
    fdStepname = new FormData();
    fdStepname.left = new FormAttachment( left, margin );
    fdStepname.top = new FormAttachment( 0, 2*margin );
    fdStepname.right = new FormAttachment( 100, 0 );
    wStepname.setLayoutData( fdStepname );

    // Connection line
    wConnection = addConnectionLine( shell, wStepname, left, 2*margin );
    if ( validator.getDatabaseMeta() == null && transMeta.nrDatabases() == 1 ) {
      wConnection.select( 0 );
    }
    wConnection.addModifyListener( lsMod );
    
    // xuxiaodong 2015年9月29日 09:57:06 增加表名输入框
    wlTable=new Label(shell, SWT.RIGHT);
	wlTable.setText("校验表名称");
	props.setLook(wlTable);
	fdlTable=new FormData();
	fdlTable.left = new FormAttachment(0, 0);
	fdlTable.right= new FormAttachment(left-2, margin);
	fdlTable.top  = new FormAttachment(wConnection, 2*margin);
	wlTable.setLayoutData(fdlTable);

	wbTable=new Button(shell, SWT.PUSH| SWT.CENTER);
		props.setLook(wbTable);
	wbTable.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
	fdbTable=new FormData();
	fdbTable.right= new FormAttachment(100, 0);
	fdbTable.top  = new FormAttachment(wConnection, 2*margin);
	wbTable.setLayoutData(fdbTable);

	wTable=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
		props.setLook(wTable);
	wTable.addModifyListener(lsMod);
	fdTable=new FormData();
	fdTable.top  = new FormAttachment(wConnection,2* margin);
	fdTable.left = new FormAttachment(left, 0);
	fdTable.right= new FormAttachment(wbTable, -margin);
	wTable.setLayoutData(fdTable);
	//徐晓东 2015年9月29日 09:57:00
	
	
    // Some buttons
    wOK = new Button( shell, SWT.PUSH );
    wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
    wCancel = new Button( shell, SWT.PUSH );
    wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
    // wHelp = createHelpButton(shell, stepMeta);

    setButtonPositions( new Button[] { wOK, wCancel }, margin, null );
    
    wlPosition = new Label( shell, SWT.NONE );
    props.setLook( wlPosition );
    fdlPosition = new FormData();
    fdlPosition.left = new FormAttachment( 0, 0 );
    fdlPosition.right = new FormAttachment( 100, 0 );
    fdlPosition.bottom = new FormAttachment( wOK, -2*margin );
    wlPosition.setLayoutData( fdlPosition );
    

    // Add listeners
    lsCancel = new Listener() {
      public void handleEvent( Event e ) {
        cancel();
      }
    };
    lsOK = new Listener() {
      public void handleEvent( Event e ) {
        ok();
      }
    };

    wCancel.addListener( SWT.Selection, lsCancel );
    wOK.addListener( SWT.Selection, lsOK );
    
    wbTable.addSelectionListener
	(
		new SelectionAdapter()
		{
			public void widgetSelected(SelectionEvent e) 
			{
				getTableName();
			}
		}
	);

    lsDef = new SelectionAdapter() {
      public void widgetDefaultSelected( SelectionEvent e ) {
        ok();
      }
    };

    wStepname.addSelectionListener( lsDef );

    // Detect X or ALT-F4 or something that kills this window...
    shell.addShellListener( new ShellAdapter() {
      public void shellClosed( ShellEvent e ) {
        checkCancel( e );
      }
    } );

    getData();
    changedInDialog = false; // for prompting if dialog is simply closed
    validator.setChanged( changed );

    // Set the shell size, based upon previous time...
    setSize();

    shell.open();
    while ( !shell.isDisposed() ) {
      if ( !display.readAndDispatch() ) {
        display.sleep();
      }
    }
    return stepname;
  }


  /**
   * Copy information from the meta-data input to the dialog fields.
   */
  public void getData() {
    if ( validator.getTableName() != null ) {
    	wTable.setText( validator.getTableName() );
    }
    if ( validator.getDatabaseMeta() != null ) {
      wConnection.setText( validator.getDatabaseMeta().getName() );
    }
    wStepname.selectAll();
    wStepname.setFocus();
  }

  private void checkCancel( ShellEvent e ) {
    if ( changedInDialog ) {
      int save = JobGraph.showChangedWarning( shell, wStepname.getText() );
      if ( save == SWT.CANCEL ) {
        e.doit = false;
      } else if ( save == SWT.YES ) {
        ok();
      } else {
        cancel();
      }
    } else {
      cancel();
    }
  }

  private void cancel() {
    stepname = null;
    validator.setChanged( changed );
    dispose();
  }

  private void getInfo( ValidatorMeta meta, boolean preview ) {
    meta.setTableName(preview && !Const.isEmpty( wTable.getText()) ? "" : wTable.getText() );
    meta.setDatabaseMeta( transMeta.findDatabase( wConnection.getText() ) );
  }

  private void ok() {
    if ( Const.isEmpty( wStepname.getText() ) ) {
      return;
    }

    stepname = wStepname.getText(); // return value
    // copy info to TextFileInputMeta class (input)

    getInfo( validator, false );

    if ( validator.getDatabaseMeta() == null ) {
      MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
      mb.setMessage( BaseMessages.getString( PKG, "TableInputDialog.SelectValidConnection" ) );
      mb.setText( BaseMessages.getString( PKG, "TableInputDialog.DialogCaptionError" ) );
      mb.open();
      return;
    }

    dispose();
  }

	private void getTableName()
	{
		// New class: SelectTableDialog
		int connr = wConnection.getSelectionIndex();
		if (connr>=0)
		{
			DatabaseMeta inf = transMeta.getDatabase(connr);
						
			if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "TableOutputDialog.Log.LookingAtConnection", inf.toString()));
		
			DatabaseExplorerDialog std = new DatabaseExplorerDialog(shell, SWT.NONE, inf, transMeta.getDatabases());
			if (std.open())
			{
              wTable.setText(Const.NVL(std.getTableName(), ""));
			}
		}
		else
		{
			MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
			mb.setMessage(BaseMessages.getString(PKG, "TableOutputDialog.ConnectionError2.DialogMessage"));
			mb.setText(BaseMessages.getString(PKG, "System.Dialog.Error.Title"));
			mb.open(); 
		}
					
	}

}
